resource "aws_instance" "device_<%= obj['ID'] %>" {

    <% if provision['AMI'] == 'default' %>
    ami                    = data.aws_ami.ubuntu2204.id
    <% else %>
    ami                    = "<%= provision['AMI'] %>"
    <% end %>

    instance_type          = "<%= provision['INSTANCETYPE'] %>"
    availability_zone      = local.my_zones[0]

    vpc_security_group_ids = [ aws_security_group.device_<%= c['ID'] %>_all.id ]

    subnet_id              = aws_subnet.device_<%= c['ID'] %>.id

    root_block_device {
        volume_size = "<%= provision['ROOT_SIZE'] %>"
    }


    <% ecidr = c['TEMPLATE']['PROVISION']['CIDR'] || "10.0.0.0/16"
       pref = ecidr.split('/').first.rpartition(".")[0]
       ip = pref << '.' << ( provision['INDEX'].to_i + 4 ).to_s
    %>

    private_ip = "<%= ip %>"

    user_data              = "<%= obj['user_data'] %>"
    tags                   = {
        Name = "<%= provision['HOSTNAME'] %>"
    }
}

<% if !ceph_vars.nil? && ceph_vars['ceph_hci'] %>

<%# additional CEPH network interface %>
resource "aws_network_interface" "device_<%= obj['ID'] %>_ceph" {
    subnet_id       = aws_subnet.device_<%= c['ID'] %>_ceph.id

    <% ecidr = c['TEMPLATE']['PROVISION']['HCI_CIDR'] || "10.1.0.0/16"
       pref = ecidr.split('/').first.rpartition(".")[0]
       ceph_ip = pref << '.' << ( provision['INDEX'].to_i + 4 ).to_s
    %>

    private_ips     = ["<%= ceph_ip %>"]
    security_groups = [ aws_security_group.device_<%= c['ID'] %>_all.id ]

    attachment {
        instance     = aws_instance.device_<%= obj['ID'] %>.id
        device_index = 1
    }

    tags                   = {
        Name = "device_<%= obj['ID'] %>_ceph"
    }

    depends_on = [ aws_instance.device_<%= obj['ID'] %> ]
}

<%# additional CEPH disk %>
resource "aws_ebs_volume" "device_<%= obj['ID'] %>_ceph_volume" {
  availability_zone = local.my_zones[0]
  size              = <%= ceph_vars['ceph_disk_size'] %>
}

resource "aws_volume_attachment" "device_<%= obj['ID'] %>_ebs_att" {
    device_name = "/dev/xvdb"
    volume_id   = aws_ebs_volume.device_<%= obj['ID'] %>_ceph_volume.id
    instance_id = aws_instance.device_<%= obj['ID'] %>.id
    stop_instance_before_detaching = true
}
<% end %>

output "device_<%= obj['ID'] %>_id" {
  value = aws_instance.device_<%= obj['ID'] %>.id
}

output "device_<%= obj['ID'] %>_ip" {
  value = aws_instance.device_<%= obj['ID'] %>.public_ip
}

